import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { DictService } from '../../../../shared/services/dict.service';
import { MaterialManageService } from '../../../../shared/services/material.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-material-add',
  templateUrl: './material-add.component.html',
  styleUrls: ['./material-add.component.scss']
})

export class MaterialAddComponent implements OnInit {

  mid: any = 0;

  validateForm: FormGroup;

  _loading: Boolean = false;
  data: Array<object>;

  Mtype: String = '';
  materialParams: any;
  materialType: Array<object>;

  searchlistError: any;

  constructor(
    private dictService: DictService,
    private route: ActivatedRoute,
    private router: Router,
    private _modal: NzModalService,
    private materialManageService: MaterialManageService,
    private _message: NzMessageService,
    private fb: FormBuilder
  ) {
    this.searchlistError = {
      bool: false,
      title: '',
    };
  }

  ngOnInit() {
    const that = this;
    this.materialType = this.dictService.UnitDataType;
    this.validateForm = this.fb.group({
      formLayout: [ 'horizontal' ],
      materialName  : [ null, [ Validators.required ] ],
      dosageSelect  : [ null, [ Validators.required ] ]
    });
    this.reset();
    this.route.queryParams
        .subscribe(res => {
          let queryParams = JSON.parse(res.item);
          // console.log(queryParams)
          if (queryParams) {
            this.materialParams.id = queryParams['id'];
            this.materialParams.name = queryParams['name'];
            this.materialParams.unit = queryParams['unit'];
            // 根据商品去修改上下架状态
            queryParams['goods'].forEach(item => {
              (function(product) {
                let param = {
                  productNo: product['sn'],
                };
                that.materialManageService.getProductList(param).subscribe(response => {
                  // console.log(response)
                  if (response['code'] === '0') {
                    that.mid++;
                    that.materialParams.materialLists.unshift({
                      mid : that.mid,
                      id: product['id'],
                      name: product['name'],
                      ylStatus: response['data'][0]['ylStatus'],
                      recomflag: product['recomflag'],
                      dosage: product['dosage'],
                      order: product['order'],
                      isNameShow: true,
                      isChecked: product['recomflag'] === 1 ? true : false,
                      sn: product['sn'],
                    });
                  }
                });
              })(item);
            });
            // this.materialParams.materialGoods = queryParams['goods'];
            this.Mtype = 'update';
          } else {
            this.Mtype = 'create';
          }
          // console.log(this.materialParams);
        });
  }

  reset(): void {
    this.materialParams = {
      id: 0,
      name: '',
      unit: '',
      materialLists: [
        {
          mid: this.mid,
          name: '',
          ylStatus: '',
          searchlist: [],
          recomflag: 0,
          dosage: '',
          order: '',
          sn: '',
        }
      ],
      materialGoods: [
        // {
        //   goods: {
        //     id: 1,
        //   },
        //   recomflag: 1,   // 1是推荐，0不是推荐
        // }
      ],
    };
  }

  changeMaterialItem(data) {
    // console.log(data);
    let material = data['searchlist'].find(i => i['id'] === data['sn']);
    const bool = this.materialParams.materialLists.find(i => i['id'] === material['id']);
    // console.log('bool:', bool);
    if (!bool) {
      if (material) {
        data['id'] = material['id'];
        data['name'] = material['name'];
        data['ylStatus'] = material['ylStatus'];
        data.isNameShow = true;
        data.sn = material['productNo'];
        // console.log(data)
        this.addMaterial();
      }
    } else {
      data.sn = data['oldSn'];
      this._message.error('已存在名为：' + material['name'] + '的关联商品,请勿重复添加。', {nzDuration: 4000});
    }
  }

  searchMaterial(e, item) {
    // console.log(e);
    let param = {
      productNo: e,
    };
    item['oldSn'] = e;
    // console.log('搜索参数: ', param)
    this.materialManageService.getProductList(param).subscribe(res => {
      // console.log(res);
      if (res['code'] === '0') {
        if (res['data'].length > 0) {
          item['searchlist'] = res['data'];
          document.getElementById('searchName').click();
          this.searchlistError = {
            bool: false,
            title: '',
          };
        } else {
          this.searchlistError = {
            bool: true,
            title: '无该编号商品',
          };
        }
      } else {
        this._message.error(`获取原料失败,${res['msg']}`, {nzDuration: 3000});
      }
    });
  }

  addMaterial() {
    this.mid++;
    this.materialParams.materialLists.push({
      mid : this.mid,
      name: '',
      ylStatus: '',
      recomflag: '',
      dosage: '',
      order: '',
      sn: '',
    });
  }

  deleteMaterial(item) {
    if (this.materialParams.materialLists.length > 1) {
      this.materialParams.materialLists.splice(this.materialParams.materialLists.findIndex(i => i['mid'] === item['mid']), 1);
    }
  }

  // 提交新增原料
  save() {
    this.submitForm();
    // console.log(this.validateForm);
    this.materialParams['name'] = this.validateForm.controls.materialName['value'];
    this.materialParams['unit'] = this.validateForm.controls.dosageSelect['value'];
    if (!this.materialParams['name'] || !this.materialParams['unit']) {
      this._message.error('原料名称和用量单位必填，请填完整再提交!', {nzDuration: 3000});
      return false;
    }
    // 格式化原料 关联商品
    // console.log(this.materialParams.materialLists);
    this.materialParams.materialGoods = [];
    this.materialParams.materialLists.forEach(material => {
      if (material.name) {
        if (material.isChecked) {
          material['recomflag'] = 1;
        } else {
          material['recomflag'] = 0;
        }
        if (!this.materialParams.materialGoods.find(i => ['id'] === material['id'])) {
          this.materialParams.materialGoods.push(material);
        }
      }
    });
    // 检测用量规格
    let dosageOrderBool = false;
    this.materialParams.materialGoods.forEach(item => {
      if (!item.dosage || item.dosage <= 0) {
        dosageOrderBool = true;
      }
    });
    if (dosageOrderBool) {
      this._message.error('用量规格必填，且用量规格要大于0，请填写完整!', {nzDuration: 3000});
      return false;
    }
    // 检测排序
    let OrderBool = false;
    this.materialParams.materialGoods.forEach(item => {
      if (!item.order || item.order < 0) {
        OrderBool = true;
      }
    });
    if (OrderBool) {
      this._message.error('排序必填，请填写完整!', {nzDuration: 3000});
      return false;
    }
    // console.log(this.Mtype);
    if (this.Mtype === 'update') {
      // 修改
      this.materialManageService.postUpdatematerial(this.materialParams)
          .subscribe(res => {
            // console.log(res);
            if (res['code'] === '0') {
              this._message.success('更新原料成功!', {nzDuration: 2000});
              this.back();
            } else {
              this._message.error(`更新原料失败,${res['msg']}`, {nzDuration: 3000});
            }
          });
    } else {
      // 新增
      this.materialManageService.postCreatematerial(this.materialParams)
          .subscribe(res => {
            // console.log(res);
            if (res['code'] === '0') {
              this._message.success('新原料创建成功!', {nzDuration: 2000});
              this.back();
            } else {
              this._message.error(`新原料创建失败,${res['msg']}`, {nzDuration: 3000});
            }
          });
    }
  }

  back(): void {
    this.router.navigate(['../'], { relativeTo: this.route, queryParamsHandling: 'preserve' });
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
  }

  get isHorizontal() {
    return this.validateForm.controls[ 'formLayout' ] && this.validateForm.controls[ 'formLayout' ].value === 'horizontal';
  }

  numberMax(size) {
    // console.log(size);
    if (size.dosage < 0) {
      size.dosage = 0;
    }
  }

}
